package com.hm.base.auto.su;

import java.lang.reflect.Field;
import java.util.Arrays;

import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;

/**
 * @author shishun.wang
 * @date 下午3:18:54 2017年6月2日
 * @version 1.0
 * @describe
 */
public class BeanUtil {

	private static final String MODEL_ID_FIELD = "id";

	public static final void copyProperties(Object source, Object target, String... ignoreProperties) {
		if (com.hm.common.util.CommonUtil.isAnyEmpty(source, target)) {
			return;
		}
		BeanUtils.copyProperties(source, target, ignoreProperties);
		// Trying copy id field

		if (com.hm.common.util.CommonUtil.isNotEmpty(ignoreProperties)
				&& Arrays.asList(ignoreProperties).contains(MODEL_ID_FIELD)) {
			return;
		}
		Field targetFiled = ReflectionUtils.findField(target.getClass(), MODEL_ID_FIELD, String.class);
		if (targetFiled == null) {
			return;
		}
		Field sourceFiled = ReflectionUtils.findField(source.getClass(), MODEL_ID_FIELD);
		if (sourceFiled == null) {
			return;
		}
		try {
			sourceFiled.setAccessible(true);
			Object sourceId = sourceFiled.get(source);
			if (sourceId == null) {
				return;
			}
			targetFiled.setAccessible(true);
			if (sourceId instanceof String) {
				ReflectionUtils.setField(targetFiled, target, sourceId);
			} else {
				ReflectionUtils.setField(targetFiled, target, sourceId.toString());
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			LoggerFactory.getLogger(BeanUtil.class).error("Failed to reflect set id properties", e);
		}

	}
}
